<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="查评事件" prop="reviewEvents">
        <el-select
          v-model="queryParams.reviewEvents"
          placeholder="请选择查评事件"
          style="width: 290px"
          clearable
          filterable
        >
          <!-- 使用 v-for 循环渲染选项 -->
          <el-option
            v-for="option in reviewEventsOptions"
            :key="option"
            :label="option"
            :value="option"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="查评要素" prop="evaluationElements">
        <el-input
          v-model="queryParams.evaluationElements"
          placeholder="请输入查评要素"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评审人" prop="examiner">
        <el-input
          v-model="queryParams.examiner"
          placeholder="请输入评审人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="责任部门" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入责任部门名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="责任人" prop="responsibleName">
        <el-input
          v-model="queryParams.responsibleName"
          placeholder="请输入责任人名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否整改" prop="isRectify">
        <el-select v-model="queryParams.isRectify" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="exportFile()"
          >导出</el-button
        >
        <el-badge value="2" class="item" style="margin-left: 10px">
          <el-button
            size="mini"
            type="warning"
            style="display: flow-root"
            @click="queryState"
            >未整改</el-button
          >
        </el-badge>
      </el-form-item>
    </el-form>

    <el-table
      id="table"
      class="rectifiication"
      v-loading="loading"
      :data="evaluationList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="操作"
        align="left"
        width="100"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >整改</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="序号" type="index" width="70" align="center" />

      <el-table-column
        label="评估项目"
        align="left"
        prop="evaluationElements"
        class=""
      >
        <template slot-scope="scope">
          <a @click.prevent="handleLinkClick(scope.row)" style="color: #409eff">
            {{ scope.row.evaluationElements }}
          </a>
        </template>
      </el-table-column>
      <el-table-column
        label="是否整改"
        sortable
        align="center"
        prop="isRectify"
        width="100"
      >
        <template slot-scope="scope">
          <el-tag
            :type="
              scope.row.isRectify === 1
                ? 'danger'
                : scope.row.isRectify === 2
                ? 'success'
                : 'danger'
            "
          >
            {{
              scope.row.isRectify == 1
                ? "未整改"
                : scope.row.isRectify == 2
                ? "已整改"
                : "未整改"
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="重大问题"
        align="center"
        prop="isGreatProblem"
        width="100"
      >
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.isGreatProblem === '0' ? 'success' : 'danger'"
          >
            {{ scope.row.isGreatProblem == 1 ? "是" : "否" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="存在问题"
        align="left"
        prop="problem"
        class="el-tooltip__popper"
      />

      <!--      <el-table-column label="评审事件" align="left" prop="reviewEvents" min-width="280" :show-overflow-tooltip="true" class="el-tooltip__popper"/>-->
      <el-table-column
        label="评审人"
        align="left"
        prop="examiner"
        width="100"
        class="el-tooltip__popper"
      />
      <!--      <el-table-column label="整改建议" align="left" prop="rectifySuggest" min-width="200" :show-overflow-tooltip="true" class="el-tooltip__popper"/>-->
      <el-table-column
        label="责任部门"
        align="left"
        prop="deptName"
        width="100"
      />
      <el-table-column
        label="责任人"
        align="left"
        prop="responsibleName"
        width="80"
      />
      <el-table-column label="整改日期" align="left" prop="okTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.okTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  getReviewEvents,
  problemRectificationList,
  getReviewEventsByPro,
  getReviewEventsFist,
} from "@/api/system/review/groping";
import * as XLSX from "xlsx/dist/xlsx.full.min.js";
import moment from "moment";
// import XLSXS from "xlsx-js-style";

export default {
  name: "Evaluation",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目查评表格数据
      evaluationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      excelSize: 10,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        reviewEvents: undefined,
        evaluationElements: undefined,
        examinerCode: undefined,
        examiner: undefined,
        isApply: undefined,
        lookWorkCase: undefined,
        evaluateCase: undefined,
        isInnovate: undefined,
        evaluateObject: undefined,
        backingMaterial: undefined,
        lookPapersCase: undefined,
        deduct: undefined,
        isProblem: undefined,
        problem: undefined,
        isGreatProblem: undefined,
        rectifySuggest: undefined,
        scenePhoto: undefined,
        reviewStatus: undefined,
        reviewStandard: undefined,
        scoreStandard: undefined,
        isDelete: undefined,
        evaGroupId: undefined,
        deptCode: undefined,
        deptName: undefined,
        responsibleCode: undefined,
        responsibleName: undefined,
        requireOkTime: undefined,
        okTime: undefined,
        requireSituation: undefined,
        okPhoto: undefined,
        deductPursuant: undefined,
      },
      reviewEventsOptions: [], // 用于存储后台返回的查评事件选项
      // 表单参数
      form: {},
      options: [
        {
          value: "2",
          label: "已整改",
        },
        {
          value: "1",
          label: "未整改",
        },
      ],
    };
  },
  created() {
    this.queryParams = Object.assign(
      this.queryParams,
      this.$route.query.queryParams
    );
    // 在组件加载后，请求后台接口获取下拉框数据
    this.fetchReviewEventsData();
    // if (undefined == this.queryParams.examiner) {
    //   this.queryParams.examiner = this.$store.state.user.nikename;
    // }
    this.getList();
  },
  methods: {
    /** 查询项目查评列表 */
    getList() {
      this.loading = true;
      problemRectificationList(this.queryParams).then((response) => {
        this.evaluationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    queryState() {
      if (this.queryParams.reviewStatus == undefined) {
        this.queryParams.reviewStatus = "未整改";
      } else {
        this.queryParams.reviewStatus = undefined;
      }
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        pageNum: 1,
        pageSize: 10,
        reviewEvents: undefined,
        groupName: undefined,
        groupLeader: undefined,
        groupLeaderCode: undefined,
        member: undefined,
        memberCode: undefined,
        creationDate: undefined,
        isDelete: undefined,
        taskAllocation: undefined,
        evaluationElements: undefined,
        standardScore: undefined,
        reviewStatus: undefined,
        reviewEventsId: undefined,
        evaluationElementsId: undefined,
        refId: undefined,
        picture: undefined,
        examinerCode: undefined,
        examiner: undefined,
        isApply: undefined,
        lookWorkCase: undefined,
        evaluateCase: undefined,
        isInnovate: undefined,
        evaluateObject: undefined,
        backingMaterial: undefined,
        lookPapersCase: undefined,
        deduct: undefined,
        isProblem: undefined,
        problem: undefined,
        isGreatProblem: undefined,
        rectifySuggest: undefined,
        scenePhoto: undefined,
        reviewStandard: undefined,
        scoreStandard: undefined,
        deptCode: undefined,
        deptName: undefined,
        responsibleCode: undefined,
        responsibleName: undefined,
        requireOkTime: undefined,
        okTime: undefined,
        requireSituation: undefined,
        okPhoto: undefined,
        deductPursuant: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 导出
    exportFile() {
      this.$confirm(
        "是否导出当前页？选择'是'导出当前页，选择'否'导出所有页",
        "提示",
        {
          distinguishCancelAndClose: true,
          confirmButtonText: "是",
          cancelButtonText: "否",
          type: "warning",
        }
      )
        .then(() => {
          this.$modal.loading("下载中");
          const params = {
            pageNum: this.queryParams.pageNum,
            pageSize: this.queryParams.pageSize,
            reviewEvents: this.queryParams.reviewEvents,
            evaluationElements: this.queryParams.evaluationElements,
            examiner: this.queryParams.examiner,
            deptName: this.queryParams.deptName,
            responsibleName: this.queryParams.responsibleName,
          };
          console.log(params);
          const self = this;
          problemRectificationList(params)
            .then((res) => {
              console.log("----", res.rows.length);
              if (res.code === 200) {
                // 解析excel文件
                const excelData = [];
                for (let i = 0; i < res.rows.length; i++) {
                  const excelObj = {};
                  excelObj.序列号 = (i + 1).toString();
                  excelObj.评估项目 = res.rows[i].evaluationElements;
                  excelObj.是否整改 =
                    res.rows[i].isRectify == 2 ? "已整改" : "未整改";
                  excelObj.重大问题 =
                    res.rows[i].isGreatProblem == 1 ? "是" : "否";
                  excelObj.存在问题 = res.rows[i].problem;
                  excelObj.评审人 = res.rows[i].examiner;
                  excelObj.责任部门 = res.rows[i].deptName;
                  excelObj.责任人 = res.rows[i].responsibleName;
                  excelObj.整改日期 = res.rows[i].okTime;
                  excelData.push(excelObj);
                }
                // debugger;
                const worksheet = XLSX.utils.json_to_sheet(excelData);
                const workbook = XLSX.utils.book_new();
                const fileName = moment().format("YYYY-MM-DD hh:mm:ss");
                let borderAll = {
                  top: {
                    style: "medium",
                  },
                  bottom: {
                    style: "medium",
                  },
                  left: {
                    style: "medium",
                  },
                  right: {
                    style: "medium",
                  },
                };
                // for(let key in worksheet){
                //   console.log('worksheet[key]',worksheet[key].t)
                //   if(worksheet[key] instanceof Object){
                //     worksheet[key].s = {
                //       border:borderAll,
                //       alignment:{
                //         horizontal:'center',
                //         vertical:'center',
                //         wrapText:1,
                //       },
                //       font:{
                //         sz:10,
                //         bold:true
                //       }
                //     }
                //   }
                // }

                // const cols = [
                //   {wch:5},
                //   {wch:30},
                //   {wch:30},
                //   {wch:30},
                //   {wch:30},
                //   {wch:30},
                //   {wch:30},
                //   {wch:30},
                //   {wch:30},
                // ]
                // worksheet['!cols'] = cols

                XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
                XLSX.writeFile(workbook, `${fileName}.xlsx`);
                self.$modal.closeLoading();
                this.$message({
                  type: "success",
                  message: "导出当前页面",
                });
              } else {
              }
            })
            .catch(() => {});
        })
        .catch((action) => {
          if (action === "cancel") {
            this.$modal.loading("下载中");
            if (
              this.queryParams.reviewEvents != undefined ||
              this.queryParams.evaluationElements != undefined ||
              this.queryParams.examiner != undefined ||
              this.queryParams.deptName != undefined ||
              this.queryParams.responsibleName != undefined
            ) {
            }

            const params = {
              pageNum: this.queryParams.pageNum,
              pageSize: this.total,
              reviewEvents: this.queryParams.reviewEvents,
              evaluationElements: this.queryParams.evaluationElements,
              examiner: this.queryParams.examiner,
              deptName: this.queryParams.deptName,
              responsibleName: this.queryParams.responsibleName,
            };
            console.log(params);
            const self = this;
            problemRectificationList(params)
              .then((res) => {
                console.log("----", res.rows.length);
                if (res.code === 200) {
                  // 解析excel文件
                  const excelData = [];
                  for (let i = 0; i < res.rows.length; i++) {
                    const excelObj = {};
                    excelObj.序列号 = (i + 1).toString();
                    excelObj.评估项目 = res.rows[i].evaluationElements;
                    excelObj.是否整改 =
                      res.rows[i].isRectify == 2 ? "已整改" : "未整改";
                    excelObj.重大问题 =
                      res.rows[i].isGreatProblem == 1 ? "是" : "否";
                    excelObj.存在问题 = res.rows[i].problem;
                    excelObj.评审人 = res.rows[i].examiner;
                    excelObj.责任部门 = res.rows[i].deptName;
                    excelObj.责任人 = res.rows[i].responsibleName;
                    excelObj.整改日期 = res.rows[i].okTime;
                    excelData.push(excelObj);
                  }
                  // debugger;
                  const worksheet = XLSX.utils.json_to_sheet(excelData);
                  const workbook = XLSX.utils.book_new();
                  const fileName = moment().format("YYYY-MM-DD hh:mm:ss");
                  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
                  XLSX.writeFile(workbook, `${fileName}.xlsx`);
                  self.$modal.closeLoading();
                  this.$message({
                    type: "success",
                    message: "导出所有页",
                  });
                } else {
                }
              })
              .catch(() => {});
          } else {
            this.$message({
              type: "info",
              message: "关闭",
            });
          }
        });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目查评";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const ID = row.id || this.ids;
      this.$router.push({
        path: "/review/localEvaluation/problemRectificationForm",
        query: { row: row, queryParams: this.queryParams },
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateEvaluation(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addEvaluation(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除项目查评编号为"' + ids + '"的数据项？')
        .then(() => {
          this.loading = true;
          return delEvaluation(ids);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/evaluation/export",
        {
          ...this.queryParams,
        },
        `evaluation_${new Date().getTime()}.xlsx`
      );
    },
    handleLinkClick(row) {
      this.$router.push({
        path: "/review/localEvaluation/problemRectificationForm",
        query: { row: row, problem: 1, queryParams: this.queryParams },
      });
    },
    // 请求后台接口获取查评事件数据
    fetchReviewEventsData() {
      getReviewEventsByPro()
        .then((response) => {
          this.reviewEventsOptions = response.data;
          // this.getFist();
        })
        .finally(() => {});
    },
    getFist() {
      getReviewEventsFist()
        .then((response) => {
          //console.log(response)
          this.queryParams.reviewEvents = response.msg;
          this.getList();
        })
        .finally(() => {});
    },
  },
};
</script>

<style>
.el-tooltip__popper {
  max-width: 30%;
  padding-bottom: 5px !important;
  display: -webkit-box;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 15;
  -webkit-box-orient: vertical;
}
.el-tooltip__popper,
.el-tooltip__popper.is-dark {
  background: rgb(48, 65, 86) !important;
  color: #fff !important;
  line-height: 24px;
}
.rectifiication .el-table__row td:nth-child(4) {
  text-indent: 1em;
}
.rectifiication .el-table__row td:nth-child(7) {
  text-indent: 1em;
}
</style>
